<template>
    <div>
        <a-row type="flex" justify="center" class="transfer">
            <a-config-provider :locale="zh_CN">
                <a-transfer
                    :target-keys="targetKeys"
                    :data-source="custRules"
                    :titles="['可使用的规则', '已使用的规则']"
                    :render="(item) => item.title"
                    @change="transferChange"
                    @selectChange="handleSelectChange"
                    :selectedKeys="selectedKeys"
                />
            </a-config-provider>
        </a-row>
        <a-form
            id="rule-form"
            :form="form"
            :label-col="{ span: 9 }"
            :wrapper-col="{ span: 8 }"
            @submit="addCustRules"
            style="width: 100%"
        >
            <a-form-item label="规则名称">
                <a-input v-decorator="['title', { rules: [{ required: true, message: '请输入规则名称' }] }]" />
            </a-form-item>
            <a-form-item label="规则描述">
                <a-input v-decorator="['desc', { rules: [{ message: '请输入规则描述' }] }]" />
            </a-form-item>
            <a-form-item label="过滤字段">
                <a-row type="flex" justify="space-between">
                    <a-col :span="18">
                        <a-input
                            v-decorator="['ruleTag', { rules: [{ required: true, message: '请输入过滤字段' }] }]"
                        />
                    </a-col>
                    <a-col><a-button @click="addTag">添加</a-button></a-col>
                </a-row>
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 8, offset: 9 }">
                <a-divider orientation="left">
                    推荐字段
                </a-divider>
                <a-tag v-for="(v, k) in suggesTags" :key="k" @click="useSuggest(v.val)">
                    {{ v.val }}
                </a-tag>
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 8, offset: 9 }">
                <a-divider orientation="left">
                    自定义字段
                </a-divider>
                <a-tag closable @close="closeTag(k)" v-for="(v, k) in tags" :key="k">
                    {{ v }}
                </a-tag>
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 8, offset: 9 }">
                <a-button html-type="submit" class="btn-margin">新增规则</a-button>
                <a-button @click="delCustRules" class="btn-margin">删除规则</a-button>
                <!-- <a-button @click="runRules" type="primary">运行规则</a-button> -->
            </a-form-item>
        </a-form>
    </div>
</template>

<script>
    import { getRuleList, useRules, setCustomRules } from '../../util/rules'
    import { segmentText } from '../../util/file-action'
    import zh_CN from 'ant-design-vue/lib/locale-provider/zh_CN'
    import { remove, concat } from 'lodash'
    export default {
        name: 'Step2',
        data() {
            return {
                custRules: [],
                targetKeys: ['0'],
                selectedKeys: [],
                zh_CN,
                form: this.$form.createForm(this, { name: 'setCustRules' }),
                tags: [],
                suggesTags: [],
            }
        },
        mounted() {
            this.suggestion()
            const list = getRuleList()
            list.forEach((v, k) => {
                const { key, title, description, rules } = v
                this.$set(this.custRules, k, {
                    key: key.toString(),
                    title,
                    description,
                    disabled: false,
                    rules,
                })
            })
        },
        watch: {},
        methods: {
            // 生成过滤字段建议
            async suggestion() {
                let suggestionList = []
                const videoList = this.$store.state.videos.videoList
                const len = videoList.length
                const findDuplicates = (arr) => {
                    let duplicates = []
                    for (let i = 0; i < arr.length; i++) {
                        let times = 0
                        for (let j = 1; j < arr.length; j++) {
                            if (arr[i] === arr[j]) {
                                const index = duplicates.findIndex(({ val }) => val === arr[i])
                                index > -1
                                    ? (duplicates[index].times = ++times)
                                    : duplicates.push({
                                          val: arr[i],
                                          times: ++times,
                                      })
                            }
                        }
                    }
                    remove(duplicates, ({ times, val }) => times < 3 || val.length < 2)
                    return duplicates.sort((a, b) => a.times > b.times)
                }
                for (let i = 0; i < len; i++) {
                    let list = await segmentText(videoList[i].name)
                    list = list.map((item) => item.w)
                    suggestionList = concat(suggestionList, list)
                    if (len - i === 1) {
                        this.suggesTags = findDuplicates(suggestionList)
                    }
                }
            },
            transferChange(nextTargetKeys) {
                this.targetKeys = nextTargetKeys
            },
            handleSelectChange(sourceSelectedKeys, targetSelectedKeys) {
                this.selectedKeys = [...sourceSelectedKeys, ...targetSelectedKeys]

                console.log('sourceSelectedKeys: ', sourceSelectedKeys)
                console.log('targetSelectedKeys: ', targetSelectedKeys)
            },
            addCustRules(e) {
                e.preventDefault()
                const { tags, custRules } = this
                const description = this.form.getFieldValue('description')
                const title = this.form.getFieldValue('title')
                const isNotNull = (val) => {
                    return val && val != ''
                }
                if (tags.length > 0 && isNotNull(description) && isNotNull(title)) {
                    const obj = {
                        key: title,
                        description: description ?? '',
                        title,
                        rules: tags,
                    }
                    this.$set(custRules, custRules.length, obj)
                    setCustomRules('add', {
                        ...obj,
                        rules: this.tags,
                    })
                    this.$nextTick(() => {
                        this.targetKeys.push(obj.key)
                    })
                    this.form.setFieldsValue({ title: '' })
                    this.tags = []
                } else {
                    this.$message.error('规则名称或者过滤字段不能为空')
                }
            },
            delCustRules() {
                const { selectedKeys, custRules } = this
                if (selectedKeys.length > 0) {
                    setCustomRules('remove', selectedKeys)
                    for (const v of selectedKeys) {
                        remove(custRules, (item) => item.key == v)
                    }
                    this.custRules = []
                    this.custRules = custRules
                    this.selectedKeys = []
                } else {
                    this.$message.warn('请至少选择一条规则')
                }
            },
            hasErrors(fieldsError) {
                return Object.keys(fieldsError).some((field) => fieldsError[field])
            },
            addTag() {
                const ruleTag = this.form.getFieldValue('ruleTag')
                if (ruleTag && ruleTag !== '') {
                    this.form.setFieldsValue({ ruleTag: '' })
                    this.tags.push(ruleTag)
                } else {
                    this.$message.error('不能添加值为空的过滤字段')
                }
            },
            closeTag(k) {
                this.tags.splice(k, 1)
            },
            async runRules() {
                const videoTemp = this.$store.state.videos.videoTemp
                const videoList = this.$store.state.videos.videoList
                for (const { key, name } of videoTemp) {
                    const { newName, cover } = await useRules(name, this.targetKeys)
                    const res = videoList.find((item) => item.key === key)
                    if (res) {
                        res.newName = newName
                        res.cover = cover
                    }
                }
                this.$store.commit('videos/setVideoTemp', [])
                this.$store.commit('videos/setVideoList', videoList)
                this.$emit('setStep', 'sub')
            },
            clearData() {
                this.selectedKeys = []
            },
            useSuggest(val) {
                this.form.setFieldsValue({ ruleTag: val })
            },
        },
    }
</script>

<style lang="less" scoped>
    .transfer {
        margin-bottom: 20px;
    }
    .btn-margin {
        margin-right: 15px;
    }
    #rule-form .ant-form-item {
        margin-bottom: 0px;
    }
</style>
